package com.yklx.youke.service;

import com.yklx.youke.entity.Session;
import com.yklx.youke.repository.SessionRepository;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;

@Service
public class ClassroomServiceImpl {

    private final SessionRepository sessionRepository;

    public ClassroomServiceImpl(SessionRepository sessionRepository) {
        this.sessionRepository = sessionRepository;
    }

    public Map<String, Object> getClassroomAccess(UUID sessionId, UUID userId) {
        Session session = sessionRepository.findById(sessionId)
                .orElseThrow(() -> new IllegalArgumentException("Session not found: " + sessionId));

        // Check if the user is authorized to access this classroom
        // Either the teacher or the student for this session
        boolean isAuthorized = session.getTeacher().getUserId().equals(userId) || 
                              session.getStudent().getStudentId().equals(userId);

        if (!isAuthorized) {
            throw new SecurityException("Unauthorized access to classroom: " + sessionId);
        }

        // Check if it's within 30 minutes of scheduled time
        long minutesBefore = java.time.Duration.between(LocalDateTime.now(), session.getScheduledTime()).toMinutes();
        boolean canAccess = minutesBefore <= 30 && minutesBefore >= 0; // Accessible 30 min before start

        return Map.of(
            "canAccess", canAccess,
            "session", session,
            "accessGranted", isAuthorized && canAccess,
            "timeUntilAccessible", Math.max(0, minutesBefore) // Minutes until accessible
        );
    }
}